package com.yy.finvideoplayer.floatwindow

import android.content.Context
import android.graphics.PixelFormat
import android.view.View
import android.view.WindowManager
import kotlin.math.abs

/**
 * 浮窗管理
 * @Description: WindowManage
 * @Author: yiw89
 * @CreateDate: 2025/9/1 14:18
 * @Version: 1.0
 */
class WindowManage(context: Context) {
    var w: Int = 0
    var h: Int = 0

    /**
     * 添加悬浮窗
     */
    fun addWindowView(view: View, windowParams: WindowManager.LayoutParams?) {
        val windowManager = getWindowManager(view.context)
        view.layoutParams = windowParams
        windowManager?.addView(view, windowParams)
    }

    /**
     * 移除悬浮窗
     */
    fun removeWindowView(view: View) {
        val windowManager = getWindowManager(view.context)
        windowManager?.removeView(view)
    }

    /**
     * 更新悬浮窗
     */
    fun updateWindowView(view: View, windowParams: WindowManager.LayoutParams?) {
        val windowManager = getWindowManager(view.context)
        windowManager?.updateViewLayout(view, windowParams)
    }


    fun creatParams(
        type: Int,
        floatParams: FloatParams
    ): WindowManager.LayoutParams {
        //系统浮窗不能超出边界,更新xy
        val ww: Int = (w - floatParams.w) / 2
        val hh: Int = (h - floatParams.h) / 2
        if (abs(floatParams.x.toDouble()) > ww) floatParams.x = if (floatParams.x > 0) ww else -ww
        if (abs(floatParams.y.toDouble()) > hh) floatParams.y = if (floatParams.y > 0) hh else -hh

        val smallWindowParams = WindowManager.LayoutParams()
        smallWindowParams.type = type
        smallWindowParams.format = PixelFormat.RGBA_8888
        smallWindowParams.flags = (WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
        //smallWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
        smallWindowParams.width = floatParams.w
        smallWindowParams.height = floatParams.h
        smallWindowParams.x = floatParams.x
        smallWindowParams.y = floatParams.y
        return smallWindowParams
    }

    private var windowManager: WindowManager? = null

    init {
        getWindowManager(context)
    }

    private fun getWindowManager(context: Context): WindowManager? {
        if (windowManager == null) {
            windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            //Point p = new Point();
        }
        if (windowManager != null) {
            h = windowManager!!.defaultDisplay.height
            w = windowManager!!.defaultDisplay.width
        }
        return windowManager
    }
}
